package com.abso.mp3tunes.locker.core.services;

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;

import com.abso.mp3tunes.locker.core.LockerServiceException;
import com.abso.mp3tunes.locker.core.data.AccountData;
import com.abso.mp3tunes.locker.core.data.LoginData;

/**
 * The MP3tunes Locker authentication service.
 */
public class AuthenticationService extends AbstractLockerService {

	/**
	 * Constructs a a new authentication service.
	 * 
	 * @param partnerToken
	 *            the partner token, which uniquely identifies and authenticates
	 *            all entities using API's to communicate with MP3tunes.com
	 */
	public AuthenticationService(String partnerToken) {
		super(partnerToken);
	}

	/**
	 * Attempts to log into the Locker service.
	 * 
	 * @param username
	 *            the username.
	 * @param password
	 *            the password.
	 * @return the login data.
	 * @throws LockerServiceException
	 *             if an error occurred communicating with the Locker
	 *             authentication service.
	 */
	public LoginData login(String username, String password)
			throws LockerServiceException {
		Map params = new HashMap();
		params.put("username", username);
		params.put("password", password);
		Document doc = executeAuthentication("login", params);
		LoginData loginData = new LoginData(doc.getRootElement());
		if (!loginData.getErrorMessage().equals("")) {
			throw new LockerServiceException("Login error: "
					+ loginData.getErrorMessage());
		} else {
			return loginData;
		}
	}

	/**
	 * Returns the account data associated with a logged user.
	 * 
	 * @param loginData
	 *            the login data returned by the <i>login</i> method.
	 * @return the account data.
	 * @throws LockerServiceException
	 *             if an error occurred communicating with the Locker
	 *             authentication service.
	 */
	public AccountData getAccountData(LoginData loginData)
			throws LockerServiceException {
		Map params = new HashMap();
		params.put("sid", loginData.getSessionId());
		Document doc = executeGeneral("accountData", params);
		return new AccountData(doc.getRootElement());
	}

}
